<template>
  <div class="container mx-auto px-4 py-8">
    <div v-if="loading" class="flex justify-center py-8">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="!groupBuy" class="text-center py-8">
      <p class="text-gray-500">团购活动不存在或已下架</p>
      <button 
        @click="$router.push('/group-buy')"
        class="mt-4 px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark transition"
      >
        返回团购列表
      </button>
    </div>

    <div v-else>
      <div class="flex flex-col md:flex-row gap-8">
        <!-- 商品图片 -->
        <div class="md:w-1/2">
          <img 
            :src="groupBuy.productImage || '/placeholder.png'" 
            :alt="groupBuy.productName"
            class="w-full h-auto rounded-lg shadow-md"
          />
        </div>

        <!-- 商品信息 -->
        <div class="md:w-1/2">
          <h1 class="text-2xl font-bold mb-4">{{ groupBuy.productName }}</h1>
          
          <div class="flex items-center mb-4">
            <span class="text-gray-500 line-through mr-3">原价: ¥{{ groupBuy.originalPrice }}</span>
            <span class="text-red-500 font-bold text-2xl">团购价: ¥{{ groupBuy.groupPrice }}</span>
          </div>
          
          <div class="bg-gray-100 p-4 rounded-lg mb-4">
            <div class="flex justify-between mb-2">
              <span class="text-gray-600">已参团人数:</span>
              <span class="font-semibold">{{ groupBuy.joinCount }}人</span>
            </div>
            <div class="flex justify-between mb-2">
              <span class="text-gray-600">成团人数:</span>
              <span class="font-semibold">{{ groupBuy.minCount }}人</span>
            </div>
            <div class="flex justify-between mb-2">
              <span class="text-gray-600">每人限购:</span>
              <span class="font-semibold">{{ groupBuy.limitPerUser }}件</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">活动状态:</span>
              <span 
                :class="[
                  'px-2 py-1 rounded text-sm',
                  getStatusClass(groupBuy.status)
                ]"
              >
                {{ getStatusText(groupBuy.status) }}
              </span>
            </div>
          </div>
          
          <div class="mb-4">
            <div class="text-gray-600 mb-2">参团进度:</div>
            <div class="w-full bg-gray-200 rounded-full h-4 mb-1">
              <div 
                class="bg-primary h-4 rounded-full" 
                :style="{width: `${Math.min(100, (groupBuy.joinCount / groupBuy.minCount) * 100)}%`}"
              ></div>
            </div>
            <div class="text-sm text-gray-500">
              还差 {{ Math.max(0, groupBuy.minCount - groupBuy.joinCount) }} 人成团
            </div>
          </div>
          
          <div class="mb-6">
            <div v-if="groupBuy.status === 1" class="text-gray-600 mb-1">
              距离结束: <span class="font-semibold">{{ formatTimeRemaining(groupBuy.endTime) }}</span>
            </div>
            <div v-if="groupBuy.status === 0" class="text-gray-600 mb-1">
              距离开始: <span class="font-semibold">{{ formatTimeRemaining(groupBuy.startTime) }}</span>
            </div>
            <div class="text-gray-600">
              活动时间: {{ formatDateTime(groupBuy.startTime) }} ~ {{ formatDateTime(groupBuy.endTime) }}
            </div>
          </div>
          
          <!-- 购买数量 -->
          <div class="bg-white rounded-lg shadow-sm mb-6 overflow-hidden">
            <div class="p-4 border-b">
              <h2 class="font-semibold">购买数量</h2>
            </div>
            <div class="p-4">
              <div class="flex items-center">
                <el-button :disabled="quantity <= 1" @click="decreaseQuantity">-</el-button>
                <span class="mx-4">{{ quantity }}</span>
                <el-button :disabled="quantity >= groupBuy.limitPerUser" @click="increaseQuantity">+</el-button>
              </div>
            </div>
          </div>

          <!-- 收货信息 -->
          <div class="bg-white rounded-lg shadow-sm mb-6 overflow-hidden">
            <div class="p-4 border-b">
              <h2 class="font-semibold">收货信息</h2>
            </div>
            <div class="p-4">
              <el-form :model="orderForm" label-width="100px">
                <el-form-item label="收货人" required>
                  <el-input v-model="orderForm.receiver" placeholder="请输入收货人姓名" />
                </el-form-item>
                <el-form-item label="手机号" required>
                  <el-input v-model="orderForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="收货地址" required>
                  <el-input v-model="orderForm.address" type="textarea" rows="3" placeholder="请输入详细收货地址" />
                </el-form-item>
              </el-form>
            </div>
          </div>
          
          <div v-if="groupBuy.status === 1" class="mb-6">
            <button 
              @click="joinGroupBuy"
              class="w-full bg-primary text-white py-3 rounded-md hover:bg-primary-dark transition"
              :disabled="isJoining"
              :class="{'opacity-50 cursor-not-allowed': isJoining}"
            >
              <span v-if="isJoining">处理中...</span>
              <span v-else>立即参团</span>
            </button>
          </div>
          
          <div v-else class="mb-6">
            <button 
              class="w-full bg-gray-300 text-gray-600 py-3 rounded-md cursor-not-allowed"
              disabled
            >
              {{ getButtonText(groupBuy.status) }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 商品详情 -->
      <div class="mt-8">
        <h2 class="text-xl font-bold mb-4 pb-2 border-b">商品详情</h2>
        <div class="product-description">
          <!-- 这里可以放商品详情，如果有HTML内容可以用v-html -->
          <p class="text-gray-600">{{ groupBuy.productName }}的详细信息</p>
        </div>
      </div>
      
      <!-- 参团须知 -->
      <div class="mt-8">
        <h2 class="text-xl font-bold mb-4 pb-2 border-b">参团须知</h2>
        <ul class="list-disc pl-5 text-gray-600">
          <li>团购商品一经售出，除质量问题外不支持退换。</li>
          <li>团购活动结束后，若未达到最低成团人数，系统将自动取消订单并退款。</li>
          <li>团购商品的发货时间可能会比普通商品略长，请耐心等待。</li>
          <li>每个用户在同一团购活动中最多可购买{{ groupBuy.limitPerUser }}件商品。</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'GroupBuyDetailView',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const groupBuy = ref(null)
    const loading = ref(true)
    const quantity = ref(1)
    const isJoining = ref(false)
    
    // 添加订单表单数据
    const orderForm = ref({
      receiver: '',
      phone: '',
      address: ''
    })
    
    const fetchGroupBuyDetail = async () => {
      loading.value = true
      try {
        const id = route.params.id
        const response = await axios.get(`/api/group-buy/${id}`)
        if (response.data.code === 200) {
          groupBuy.value = response.data.data
        } else {
          console.error('获取团购详情失败:', response.data.message)
        }
      } catch (error) {
        console.error('获取团购详情出错:', error)
      } finally {
        loading.value = false
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '未开始'
        case 1: return '进行中'
        case 2: return '已结束'
        case 3: return '已取消'
        default: return '未知状态'
      }
    }

    const getStatusClass = (status) => {
      switch (status) {
        case 0: return 'bg-blue-100 text-blue-800'
        case 1: return 'bg-green-100 text-green-800'
        case 2: return 'bg-gray-100 text-gray-800'
        case 3: return 'bg-red-100 text-red-800'
        default: return 'bg-gray-100 text-gray-800'
      }
    }

    const getButtonText = (status) => {
      switch (status) {
        case 0: return '即将开始'
        case 1: return '立即参团'
        case 2: return '已结束'
        case 3: return '已取消'
        default: return '查看详情'
      }
    }
    
    const formatTimeRemaining = (timeString) => {
      const targetTime = new Date(timeString)
      const now = new Date()
      const diff = targetTime - now
      
      if (diff <= 0) return '已结束'
      
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      
      if (days > 0) {
        return `${days}天${hours}小时`
      } else if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      } else {
        return `${minutes}分钟`
      }
    }
    
    const formatDateTime = (timeString) => {
      const date = new Date(timeString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    const decreaseQuantity = () => {
      if (quantity.value > 1) {
        quantity.value--
      }
    }
    
    const increaseQuantity = () => {
      if (quantity.value < groupBuy.value.limitPerUser) {
        quantity.value++
      }
    }
    
    const joinGroupBuy = async () => {
      if (isJoining.value) return
      
      // 验证收货信息
      if (!orderForm.value.receiver || !orderForm.value.phone || !orderForm.value.address) {
        ElMessage.warning('请填写完整的收货信息')
        return
      }

      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(orderForm.value.phone)) {
        ElMessage.warning('请输入正确的手机号')
        return
      }
      
      isJoining.value = true
      try {
        // 检查用户是否登录
        const token = localStorage.getItem('token')
        if (!token) {
          router.push(`/login?redirect=/group-buy/${route.params.id}`)
          return
        }
        
        // 创建团购订单
        const response = await axios.post('/api/group-buys/orders', {
          groupBuyId: groupBuy.value.id,
          quantity: quantity.value,
          receiver: orderForm.value.receiver,
          phone: orderForm.value.phone,
          address: orderForm.value.address
        })
        
        if (response.data.code === 200) {
          ElMessage.success('参团成功')
          // 刷新团购详情数据
          await fetchGroupBuyDetail()
        } else {
          ElMessage.error(response.data.message || '参团失败，请稍后重试')
        }
      } catch (error) {
        console.error('参团出错:', error)
        ElMessage.error('参团失败，请稍后重试')
      } finally {
        isJoining.value = false
      }
    }
    
    onMounted(fetchGroupBuyDetail)
    
    return {
      groupBuy,
      loading,
      quantity,
      isJoining,
      orderForm,
      getStatusText,
      getStatusClass,
      getButtonText,
      formatTimeRemaining,
      formatDateTime,
      decreaseQuantity,
      increaseQuantity,
      joinGroupBuy
    }
  }
}
</script> 